package logic

import (
	"code-guard/model/cache"
	"code-guard/model/mysql"
	"code-guard/pkg"
	"context"
	"errors"

	"code-guard/coderpc/coderpc"
	"code-guard/coderpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *coderpc.RegisterRequest) (*coderpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	result, _ := cache.Rdb.Get(l.ctx, "cache_"+in.Tel).Result()
	if in.SmsCode != result {
		return nil, errors.New("验证码错误，请重新输入")
	}

	mysql.DB.Debug().Where("username = ?", in.Username).Find(&user)
	if user.ID != 0 {
		return nil, errors.New("当前账号已存在，请更换")
	}

	m := mysql.User{

		Username: in.Username,
		Password: pkg.Md5(in.Password),
		Tel:      in.Tel,
	}

	err := mysql.DB.Debug().Create(&m).Error
	if err != nil {
		return nil, err
	}

	return &coderpc.RegisterResponse{
		UserId: int64(m.ID),
	}, nil
}
